from appserver import db_store
from sqlalchemy import func
import copy


class ModelBase(db_store.Model):
    __abstract__ = True    # 使ModelBase不必与数据表关联

    id = db_store.Column(db_store.Integer, primary_key=True, comment=u'主键')

    def __init__(self):
        self.id = 0

    def from_dict(self, source):
        for k in source:
            try:
                getattr(self, k)
            except AttributeError as e:
                print(e)
                raise RuntimeError("数据格式错误")
            setattr(self, k, source[k])

    def to_dict(self):
        return {c.name: getattr(self, c.name, None) for c in self.__table__.columns}

    def get_max_id(self):
        val = db_store.session.query(func.max(self.__class__.id)).scalar()
        if not val:
            return 0
        else:
            return val

    def save(self):
        try:
            if self.id == 0:  # 新增数据
                self.id = self.get_max_id() + 1
            db_store.session.add(self)
            db_store.session.commit()
            return True
        except Exception as err:
            print(err)
            db_store.session.rollback()
            return False

    def delete(self):
        try:
            db_store.session.delete(self)
            db_store.session.commit()
            return True
        except Exception as err:
            print(err)
            db_store.session.rollback()
            return False

    def get_entity_by_id(self, id):
        return copy.deepcopy(self.query.filter_by(id=id).first())

    def get_list_all(self):
        return self.query.all()
